/**
 * 区域奖励算法
 */
const calcReward = async function(data) {
	let userRewardList = [];

	let {
		orderInfo, // 订单信息
		userInfo, // 下单人信息
		mchInfo, // 商家配置信息
	} = data;
	let { goods_sku_list } = orderInfo;
	// 如果没有上级,则无需计算
	if (vk.pubfn.isNull(userInfo.inviter_uid)) {
		return [];
	}
	const maxCeng = 2; // 最大2级分销
	let level_rule = vk.pubfn.getData(mchInfo, "fx.level_rule");

	// 循环上级（最多循环2次）
	for (let i = 0; i < maxCeng; i++) {
		let level = i + 1; // 当前第几级
		let rewardKeyName = `share_reward_${level}`;
		let sumUserReward = 0; // 该用户总奖励
		let goods_reward_list = []; // 商品奖励明细
		let user_id = userInfo.inviter_uid[i];
		if (vk.pubfn.isNull(user_id)) {
			continue;
		}
		let calcUser = await vk.daoCenter.userDao.findById(user_id);
		if (vk.pubfn.isNull(calcUser)) {
			continue;
		}
		// 如果该用户不是分销员，则不能获得奖励
		if (!calcUser.fx.is_fx) {
			console.log(`用户【${calcUser._id}（${calcUser.nickname}）】不是分销员，无法获得奖励。跳过此用户的奖励计算。`)
			continue;
		}
		let levelK = 1; // 用户分销等级系数
		// 如果用户有分销等级,且商品受等级系数影响,则需要乘以用户分销等级系数
		if (vk.pubfn.isNotNull(level_rule)) {
			let calcLevelRule = vk.pubfn.getListItem(level_rule, "lv", calcUser.fx.lv);
			if (vk.pubfn.isNotNull(calcLevelRule) && vk.pubfn.isNotNull(calcLevelRule[rewardKeyName])) {
				levelK = calcLevelRule[rewardKeyName];
				if (levelK < 0) levelK = 0;
			}
		}

		// 循环商品
		for (let j = 0; j < goods_sku_list.length; j++) {
			let goodsItem = goods_sku_list[j];
			let {
				reward_rule = {}, // 奖励规则
					should_payment_amount, // 应付金额
					buy_num, // 购买数量
			} = goodsItem;
			if (reward_rule.is_custom === -1) {
				// 无奖励
				continue;
			}

			let goodsReward = {
				sku_id: goodsItem._id,
				goods_id: goodsItem.goods_id,
				buy_num: goodsItem.buy_num,
				should_payment_amount: goodsItem.should_payment_amount,
				reward_value: 0, // 奖励金额（分为单位）
				reward_value_format: 0, // 奖励金额（元为单位）
				reward_formula: "", // 计算公式（元为单位）
			};

			// 判断该商品是否有自定义奖励规则
			if (reward_rule.is_custom === 1) {
				// 自定义规则
				let itemRewardRule = reward_rule[rewardKeyName] || {};
				if (!itemRewardRule.is_calc) {
					continue;
				}
				let goodsLevelK = 1;
				// 如果使用了自定义规则,判断商品是否支持分销等级系数
				if (itemRewardRule.is_level_k) {
					goodsLevelK = levelK;
				}
				if (itemRewardRule.is_fixed_calc) {
					// 固定
					let fixed_value = itemRewardRule.fixed_value;
					goodsReward.reward_value = vk.pubfn.toDecimal(fixed_value * buy_num * goodsLevelK, 0);
					goodsReward.reward_value_format = vk.pubfn.toDecimal(goodsReward.reward_value / 100, 2);
					goodsReward.reward_formula = `${vk.pubfn.toDecimal(fixed_value / 100, 2)} * ${buy_num} * ${goodsLevelK} = ${goodsReward.reward_value_format}`;
				} else {
					// 百分比
					let k = itemRewardRule.proportion_value;
					goodsReward.reward_value = vk.pubfn.toDecimal(should_payment_amount * k * goodsLevelK, 0);
					goodsReward.reward_value_format = vk.pubfn.toDecimal(goodsReward.reward_value / 100, 2);
					goodsReward.reward_formula = `${vk.pubfn.toDecimal(should_payment_amount / 100, 2)} * ${k} * ${goodsLevelK} = ${goodsReward.reward_value_format}`;
				}
			} else {
				// 默认规则
				let k = vk.pubfn.getData(mchInfo, `fx.${rewardKeyName}`, 0);
				goodsReward.reward_value = vk.pubfn.toDecimal(should_payment_amount * k * levelK, 0);
				goodsReward.reward_value_format = vk.pubfn.toDecimal(goodsReward.reward_value / 100, 2);
				goodsReward.reward_formula = `${vk.pubfn.toDecimal(should_payment_amount / 100, 2)} * ${k} * ${levelK} = ${goodsReward.reward_value_format}`;
			}
			// 如果该商品实付金额小于奖励支出，为了商家利益，此商品不返佣
			if (goodsItem.should_payment_amount >= goodsReward.reward_value) {
				goods_reward_list.push(goodsReward);
				sumUserReward += goodsReward.reward_value; // 已分为单位
			}
		}
		let calc_amount = orderInfo.amount_info.payment_amount - orderInfo.amount_info.express_amount; // 付款金额，去除运费
		// 只有订单商品合计付款金额 > 0，且奖励 > 0 才添加
		if (calc_amount > 0 && sumUserReward > 0) {
			userRewardList.push({
				user_id: calcUser._id, // 奖励归属人id
				reward_value: vk.pubfn.toDecimal(sumUserReward, 0), // 该用户总奖励（已分为单位）
				reward_value_format: vk.pubfn.toDecimal(sumUserReward / 100, 2), // 该用户总奖励（以元为单位）
				goods_reward_list, // 各商品奖励明细
				reward_type: 1, // 0: 未分类奖励 1:二级分销  2:区域奖励
				reward_type_lv: level, // 层级
				reward_name: level == 1 ? "直推奖励" : "间推奖励",
				calc_rule: {
					calc_amount: vk.pubfn.toDecimal(calc_amount / 100, 2), // 付款金额，去除运费
					reward_value: vk.pubfn.toDecimal(sumUserReward / 100, 2),
					k: calc_amount > 0 ? vk.pubfn.toDecimal(sumUserReward / calc_amount, 6) : 0,
				}
			});
		}
	}

	return userRewardList;
};

module.exports = calcReward;
